package 实验四6;

public class MultiThreadSum {
    public static void main(String[] args) throws InterruptedException {
        // 创建大型数组
        int[] array = new int[1000000];
        for (int i = 0; i < array.length; i++) {
            array[i] = i + 1;
        }

        int threadCount = 4;
        int chunkSize = array.length / threadCount;
        Thread[] threads = new Thread[threadCount];
        SumTask[] tasks = new SumTask[threadCount];

        for (int i = 0; i < threadCount; i++) {
            int start = i * chunkSize;
            int end = (i == threadCount - 1) ? array.length : start + chunkSize;
            tasks[i] = new SumTask(array, start, end);
            threads[i] = new Thread(tasks[i]);
            threads[i].start();
        }

        for (Thread thread : threads) {
            thread.join();
        }

        long totalSum = 0;
        for (SumTask task : tasks) {
            totalSum += task.getSum();
        }

        System.out.println("数组总和: " + totalSum);
    }

    static class SumTask implements Runnable {
        private final int[] array;
        private final int start;
        private final int end;
        private long sum;

        public SumTask(int[] array, int start, int end) {
            this.array = array;
            this.start = start;
            this.end = end;
        }

        @Override
        public void run() {
            sum = 0;
            for (int i = start; i < end; i++) {
                sum += array[i];
            }
        }

        public long getSum() {
            return sum;
        }
    }
}
